package ctm.javacode;

import java.io.* ;
import java.sql.*;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sun.mail.handlers.message_rfc822;

import java.security.AccessControlException;

@WebServlet("/login.do")

public class login extends HttpServlet {
	
	private final String SUCCESS_VIEW = "main.jsp"; 
	private final String ERROR_VIEW = "loginError.jsp"; 
	
	
	protected void doPost(HttpServletRequest request,
								HttpServletResponse response )
								throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		password = md5Encrypt.generate(password);//用md5加密帳戶密碼
	
		if ( request.isUserInRole("admin") || //已經登入的使用者先讓他登出
				 request.isUserInRole("user") ||
				 request.isUserInRole("manager") || request.isUserInRole("professional")) {		
				request.logout();
			} // end if
		
		try {
			if (checkLogin(username, password))
			{
				request.login(username,password);				
				HttpSession session = request.getSession();
				session.setAttribute("login", username);
				request.getRequestDispatcher(SUCCESS_VIEW)
					   .forward(request, response);
				} // end if
			else
			{
				response.sendRedirect(ERROR_VIEW);
				} // end else
		} catch (SQLException e) {
				
			e.printStackTrace();
		} // end catch
		catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // end catch			
	} // end doPost()
	
	
	private boolean checkLogin(String username, String password) throws SQLException, NamingException {
		
		Boolean isUser = false ;
		dbBean db = new dbBean("jdbc/ctmpllab") ;
		ResultSet rs ;
		//System.out.println(password);
		db.Connected();		
		try {
			rs = db.ExcuteQuery("SELECT * FROM accounttable");		    
		} catch(SQLException e) {
			throw new SQLException(e) ;
		} // end try-catch
			
		while ( rs.next() ) {
			if (rs.getString("account").trim().equals(username) &&
					rs.getString("password").trim().equals(password)) {
				isUser = true ;
			} // end if
		} // end while
		db.CloseConn() ; // 關閉資料庫
		
		
		return isUser ;
	} // end checkLogin()
	
} // end class login()




